<template>
    <div class="contract-form">
        <!-- 基本信息 -->
        <h3>基本信息</h3>
        <el-form :model="form" :rules="rules" ref="contractForm" label-width="120px" class="basic-info">
            <el-row :gutter="20">
                <!-- 原有表单字段保持完整 -->
                <el-col :span="8">
                    <el-form-item label="所属小区" prop="communityId">
                        <el-select v-model="form.communityId" placeholder="请选择小区" style="width: 100%;"
                            @change="handleCommunityChange" clearable>
                            <el-option v-for="item in communityOptions" :key="item.id" :label="item.communityName"
                                :value="item.communityId"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <!-- 其他表单项保持不变 -->
            </el-row>
        </el-form>

        <!-- 合同信息 -->
        <h3>合同信息</h3>
        <el-form :model="form" :rules="rules" ref="contractForm" label-width="120px" class="contract-info">
            <el-row :gutter="20">
                <!-- 原有合同信息字段保持完整 -->
                <el-col :span="8">
                    <el-form-item label="合同编号" prop="contractNumber">
                        <el-input v-model="form.contractNumber" placeholder="请输入合同编号" style="width: 100%;" />
                    </el-form-item>
                </el-col>
                <!-- 其他表单项保持不变 -->
            </el-row>
        </el-form>

        <!-- 操作按钮 -->
        <div class="button-group" style="text-align: right; margin-right: 30px;">
            <el-button type="primary" @click="handleSave" :loading="loading">提交</el-button>
            <el-button @click="goBack">取消</el-button>
        </div>
    </div>
</template>

<script>
import request, { communityRequest } from '@/utils/request';

export default {
    name: 'AddAdvertisingLease',
    data() {
        // 自定义验证规则
        const validatePhone = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('请输入联系电话'));
            }
            if (!/^1[3-9]\d{9}$/.test(value)) {
                return callback(new Error('请输入正确的手机号码'));
            }
            callback();
        };

        const validateDate = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('请选择日期'));
            }
            callback();
        };

        return {
            feeAmount: 0,
            brokerage: 0,
            TotalAmount: 0,
            loading: false,
            form: {
                communityId: "",
                advertisingId: "",
                depositId: 1,
                contractNumber: "",
                leaseCompany: "",
                leaseName: "",
                leasePhone: "",
                tenantName: "",
                tenantPhone: "",
                legalRepresentative: "",
                collectionArea: "",
                signingDate: "",
                leaseTerm: 1,
                startDate: "",
                stopDate: "",
                depositDescription: "",
                remarks: "",
                advertisingPosition: "",
                advertisingSize: ""
            },
            communityOptions: [],
            advertisingOptions: [],
            depositOptions: [],
            rules: {
                // 保持原有验证规则不变
                communityId: [{ required: true, message: '请选择小区', trigger: 'change' }],
                advertisingId: [{ required: true, message: '请选择广告位', trigger: 'change' }],
                leaseCompany: [{ required: true, message: '请输入租赁方', trigger: 'blur' }],
                leaseName: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
                leasePhone: [{ required: true, validator: validatePhone, trigger: 'blur' }],
                contractNumber: [{ required: true, message: '请输入合同编号', trigger: 'blur' }],
                tenantName: [{ required: true, message: '请输入承租方', trigger: 'blur' }],
                signingDate: [{ required: true, validator: validateDate, trigger: 'change' }],
                legalRepresentative: [{ required: true, message: '请输入法定代表', trigger: 'blur' }],
                tenantPhone: [{ required: true, validator: validatePhone, trigger: 'blur' }],
                leaseTerm: [
                    { required: true, message: '请输入租期', trigger: 'blur' },
                    { type: 'number', message: '租期必须为数字', trigger: 'blur' }
                ],
                startDate: [{ required: true, validator: validateDate, trigger: 'change' }],
                stopDate: [{ required: true, validator: validateDate, trigger: 'change' }],
                depositId: [{ required: true, message: '请选择租金方式', trigger: 'change' }]
            }
        }
    },
    methods: {
        async handleSave() {
            try {
                // 表单验证
                const valid = await this.$refs.contractForm.validate();
                if (!valid) {
                    this.$message.error('请完善表单信息');
                    return;
                }

                this.loading = true;

                // 构造提交数据
                const submitData = {
                    ...this.form,
                    signingDate: this.formatDate(this.form.signingDate),
                    startDate: this.formatDate(this.form.startDate),
                    stopDate: this.formatDate(this.form.stopDate),
                    advertisingPrice: this.feeAmount,
                    totalAmount: this.TotalAmount
                };

                // 提交表单到后端接口
                const res = await request.post('/advertisingLease/addAdvertisingLease', submitData);

                // 调用支付接口
                const billId = res.data.billId; // 假设后端返回的响应中包含 billId
                const payRes = await request.post('/billPay/payOrder', { billId });

                // 获取支付宝沙箱的HTML内容
                const alipayHtml = payRes.data;

                // 打开新窗口并写入支付宝HTML内容
                const payWindow = window.open('', '_blank');
                payWindow.document.write(alipayHtml);
                payWindow.document.close();

                // 监听新窗口关闭事件
                const timer = setInterval(() => {
                    if (payWindow.closed) {
                        clearInterval(timer);
                        this.$message.success('支付流程已完成');
                        this.$router.push({ name: 'AdvertisingSpace' }); // 支付完成后跳转到广告位列表页
                    }
                }, 500);

            } catch (err) {
                console.error('操作失败:', err);
                this.$message.error(err.message || '提交失败');
            } finally {
                this.loading = false;
            }
        },
        // 保持其他原有方法不变
        getCommunity() {
            communityRequest.get('/community/selcomm')
                .then(res => this.communityOptions = res.data || [])
                .catch(() => this.$message.error('获取小区列表失败'));
        },
        handleCommunityChange(communityId) {
            // 原有逻辑保持不变
        },
        // 其他方法保持不变...
    }
}
</script>

<style scoped>
.contract-form {
    padding: 20px;
}

h3 {
    margin-bottom: 15px;
    font-size: 16px;
    font-weight: bold;
}

.basic-info,
.contract-info {
    margin-bottom: 20px;
}

.el-form-item {
    margin-bottom: 15px;
}

.button-group {
    margin-top: 20px;
}
</style>
